﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using WinHBM.Core.Bluetooth;
using WinHBM.Core.DB;
using WinHBM.Core.Net.Http;

namespace WinHBM.Core.Task
{
    public class UploadFlowerTask
    {

        private static readonly log4net.ILog Logger = log4net.LogManager.GetLogger(typeof(UploadFlowerTask));
        private static string TABLE_FLOWER_LOG = "flowerLog";
        private static string RequestPrefix;
        private static Thread thread;

        public static void Start()
        {
            if (!TokenHolder.isLogin)
            {
                return;
            }
            thread = new Thread(DoTask);
            thread.Name = "UploadFlowerTask";
            thread.IsBackground = true;
            thread.Start();
        }

        public static void Stop()
        {
            if (thread == null || thread.IsAlive == false)
            {
                return;
            }

            thread.Abort();
        }

        private static void DoTask()
        {
            Logger.Debug("UploadFlowerTask is running");
            try {
                NameValueCollection appSettings = ConfigurationSettings.AppSettings;
                RequestPrefix = appSettings["apiHost"];
                while (true)
                {
                    Thread.Sleep(1000);
                    
                    UploadFlower();
                    
                }
            }
            catch (Exception e) {
                Logger.Equals(e);
            }
        }

        /**
         * 读取红花记录表，上传成功删除记录，上传不成功保留记录，
         */
        private static void UploadFlower()
        {
            try
            {
                //查询红花记录表
                List<Dictionary<string, string>> SQLResult = SQLiteHelper.Instance.findAll(TABLE_FLOWER_LOG);
                if (SQLResult.Count <= 0) return;

                foreach (Dictionary<string, string> dic in SQLResult)
                {
                    //上传 
                    JObject obj = new JObject();
                    obj["sender_user_role_id"] = dic["teacherId"];
                    obj["baby_id"] = dic["babyId"];
                    obj["flower_time"] = dic["time"];
                    if (dic["type"].ToString().Equals(Convert.ToInt32(FlowerType.Red).ToString()))
                    {
                        obj["type"] = "0";
                    }
                    else if (dic["type"].ToString().Equals(Convert.ToInt32(FlowerType.Gold).ToString()))
                    {
                        obj["type"] = "1";
                    }
                    JObject result = DoRequest("/api/flower/inc", RequestMethod.POST, obj);
                    //成功 删除 数据记录
                    if (result.ContainsKey("errcode" ) && result["errcode"].ToString().Equals("0"))
                    {
                        SQLiteHelper.Instance.delete(TABLE_FLOWER_LOG, dic);
                    }
                }
            }
            catch (Exception e)
            {
                string msg = e.Message;
            }

        }

        private static JObject DoRequest(string url, RequestMethod method, JObject body)
        {
            string result;
            try
            {

                if (!url.StartsWith("http") && !url.StartsWith("https"))
                {
                    url = RequestPrefix + url;
                }

                if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
                {
                    ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                }

                HttpWebRequest webReq = HttpWebRequest.Create(url) as HttpWebRequest;
                webReq.Method = method.ToString();
                webReq.ContentType = "application/json";
                if (!String.IsNullOrEmpty(TokenHolder.Token))
                {
                    webReq.Headers["Authorization"] = "Bearer " + TokenHolder.Token;
                }

                if (method.Equals(RequestMethod.POST) && body != null)
                {
                    byte[] btBodys = Encoding.UTF8.GetBytes(body.ToString());
                    webReq.ContentLength = btBodys.Length;
                    Stream bodyStream = webReq.GetRequestStream();
                    bodyStream.Write(btBodys, 0, btBodys.Length);
                    bodyStream.Close();
                }


                HttpWebResponse webResponse = (HttpWebResponse)webReq.GetResponse();
                StreamReader steamReader = new StreamReader(webResponse.GetResponseStream(), Encoding.UTF8);
                result = steamReader.ReadToEnd();

                steamReader.Close();
                //webReq.Abort();
                webResponse.Close();
            }
            catch (Exception e)
            {
                Dictionary<String, Object> ExceptionDic = new Dictionary<String, Object>();
                ExceptionDic.Add("errcode", -1);
                ExceptionDic.Add("message", e.Message);
                result = JsonConvert.SerializeObject(ExceptionDic);
                Logger.Error(e);
            }

            return JObject.Parse(result);
        }


        private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
        {
            return true; //总是接受  
        }


    }
}
